<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="1100px">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      vloading="formLoading"
      :inline="true"
      label-width="auto"
    >
      <el-form-item label="套餐" prop="comboId">
        <el-select
          v-model="formData.comboId"
          placeholder="请选择套餐"
          :clearable="true"
          :disabled="isShow"
        >
          <el-option
            v-for="dict in comboList"
            :key="dict.id"
            :label="dict.comboName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="计划名称" prop="planName">
        <el-input
          v-model="formData.planName"
          placeholder="请输入计划名称"
          :clearable="true"
          :disabled="isShow"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="beginTime">
        <el-date-picker
          v-model="formData.beginTime"
          placeholder="请输入开始时间"
          :clearable="true"
          value-format="YYYY-MM-DD"
          @change="handleBeginTimeChange"
          :disabled="isShow"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="formData.endTime"
          placeholder="请输入结束时间"
          value-format="YYYY-MM-DD"
          disabled
        />
      </el-form-item>
    </el-form>
    <Table
      :columns="columns"
      :adaptive="true"
      :data="formData.details"
      @row-click="handleRowClick"
      @cell-click="handleCellClick"
    >
      <template #breakfast="{ row }">
        {{
          row.breakfast
            .map((dish) => {
              return dish.name
            })
            .join(',')
        }}
      </template>
      <template #lunch="{ row }">
        {{
          row.lunch
            .map((dish) => {
              return dish.name
            })
            .join(',')
        }}
      </template>
      <template #dinner="{ row }">
        {{
          row.dinner
            .map((dish) => {
              return dish.name
            })
            .join(',')
        }}
      </template>
    </Table>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <RestaurantRecipeSelect ref="recipeSelectRef" @select-value="handleSelectRecipe" />
</template>
<script setup name="RestaurantPlanEdit" lang="ts">
import * as RestaurantRecipeApi from '@/api/restaurant/recipe'
import * as RestaurantPlanApi from '@/api/restaurant/plan'
import * as RestaurantPlanDetailModel from '@/model/restaurant/plan/RestaurantPlanDetail'
import * as RestaurantPlanModel from '@/model/restaurant/plan/RestaurantPlan'
import RestaurantRecipeSelect from '../restaurantRecipe/RestaurantRecipeSelect.vue'
import { addTime, formatDate } from '@/utils/formatTime'
import { DICT_TYPE, getDictObj } from '@/utils/dict'
import { RestaurantPlanStatusEnum } from '@/utils/constants'
interface RestaurantPlanEdit extends RestaurantPlanModel.RestaurantPlan {
  details: RestaurantPlanDetailModel.RestaurantPlanDetail[]
}
interface RestaurantPlanTable {
  id: number | undefined
  comboId: string
  planName: string
  planStatus: number
  beginTime: Date | undefined
  endTime: string | undefined
  details: any[]
}
const recipeSelectRef = ref()
const dialogTitle = ref('')
const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
let formType = ''
const comboList = ref()
const message = useMessage()
const { t } = useI18n()
const clickRow = ref()
const clickCell = ref()
const isShow = ref(false)
const formData = ref<RestaurantPlanTable>({
  id: undefined,
  planName: '',
  comboId: '',
  beginTime: undefined,
  endTime: undefined,
  planStatus: 1,
  details: [
    { time: '星期一', breakfast: [], lunch: [], dinner: [] },
    { time: '星期二', breakfast: [], lunch: [], dinner: [] },
    { time: '星期三', breakfast: [], lunch: [], dinner: [] },
    { time: '星期四', breakfast: [], lunch: [], dinner: [] },
    { time: '星期五', breakfast: [], lunch: [], dinner: [] },
    { time: '星期六', breakfast: [], lunch: [], dinner: [] },
    { time: '星期日', breakfast: [], lunch: [], dinner: [] }
  ]
})
const formRules = reactive({
  planName: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
  comboId: [{ required: true, message: '请选择套餐', trigger: 'change' }],
  beginTime: [{ required: true, type: 'date', message: '请输入开始时间', trigger: 'change' }]
})
const tableCurrentRow = ref()
const columns = [
  {
    label: '时间',
    prop: 'time'
  },
  {
    label: '早餐',
    prop: 'breakfast',
    slot: 'breakfast'
  },
  {
    label: '午餐',
    prop: 'lunch',
    slot: 'lunch'
  },
  {
    label: '晚餐',
    prop: 'dinner',
    slot: 'dinner'
  }
]
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType = type
  comboList.value = await RestaurantRecipeApi.listQueryCombo()
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const planData = await RestaurantPlanApi.get(id)
      if (planData.planStatus == RestaurantPlanStatusEnum.PUBLISH) {
        isShow.value = true
      }
      formData.value.id = planData.id
      formData.value.beginTime = planData.beginTime
      formData.value.endTime = planData.endTime
      formData.value.comboId = planData.comboId
      formData.value.planStatus = planData.planStatus
      formData.value.planName = planData.planName
      planData.details.forEach((detail) => {
        formData.value.details[detail.week - 1][
          getDictObj(DICT_TYPE.COMMON_MEAL, detail.meal).dataEnum.toLowerCase()
        ].push(detail.dish)
      })
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = () => {
  isShow.value = false
  formData.value = {
    id: undefined,
    planName: '',
    comboId: '',
    beginTime: undefined,
    endTime: undefined,
    planStatus: 1,
    details: [
      { time: '星期一', breakfast: [], lunch: [], dinner: [] },
      { time: '星期二', breakfast: [], lunch: [], dinner: [] },
      { time: '星期三', breakfast: [], lunch: [], dinner: [] },
      { time: '星期四', breakfast: [], lunch: [], dinner: [] },
      { time: '星期五', breakfast: [], lunch: [], dinner: [] },
      { time: '星期六', breakfast: [], lunch: [], dinner: [] },
      { time: '星期日', breakfast: [], lunch: [], dinner: [] }
    ]
  }
  formRef.value?.resetFields()
}

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = {
      id: formData.value.id,
      comboId: formData.value.comboId,
      beginTime: formData.value.beginTime,
      endTime: formData.value.endTime,
      planStatus: formData.value.planStatus,
      planName: formData.value.planName,
      details: []
    } as unknown as RestaurantPlanEdit
    formData.value.details.forEach((detail, index) => {
      ;['breakfast', 'lunch', 'dinner'].forEach((meal, mealIndex) => {
        if (detail[meal].length > 0) {
          detail[meal].forEach((dish) => {
            data.details.push({
              id: undefined,
              meal: mealIndex + 1,
              week: index + 1,
              dishId: dish.id,
              planId: formType === 'create' ? undefined : formData.value.id
            })
          })
        }
      })
    })

    if (formType === 'create') {
      await RestaurantPlanApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      await RestaurantPlanApi.update(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** table行点击事件 */
const handleRowClick = (row) => {
  tableCurrentRow.value = row
}

const handleCellClick = (row, column) => {
  if (isShow.value) return
  if (!['breakfast', 'lunch', 'dinner'].includes(column.property)) return
  clickRow.value = row
  clickCell.value = column.property
  recipeSelectRef.value.open(clickRow.value[clickCell.value])
}

const handleSelectRecipe = (recipeList) => {
  clickRow.value[clickCell.value] = recipeList
}

const handleBeginTimeChange = () => {
  if (formData.value.beginTime != null)
    formData.value.endTime = formatDate(addTime(formData.value.beginTime, 6 * 24 * 3600 * 1000))
}
</script>
